import { useState, useEffect } from "react";
import { Input } from "antd";
interface CommonRangeProps {
	max?: number;
	min?: number;
	onChange?: any;
	value?: any;
}

function CommonRange(props: CommonRangeProps) {
	const { max = 100, min = 0, onChange = () => {} } = props;
	const [A, setA] = useState("");
	const [B, setB] = useState("");
	const testInput = (e: any, type: any) => {
		let str = e.target.value.trim();
		if (/(\.|[0-9])/.test(str.slice(str.length - 1)) || !str) {
			if (min > Number(str) || max < Number(str)) {
				return;
			}
			if (type === "A") {
				setA(str);
			} else {
				setB(str);
			}
		}
	};
	useEffect(() => {
		if (!!B && !!A) {
			onChange([A, B]);
		}
		// eslint-disable-next-line
	}, [A, B]);
	useEffect(() => {
		if (!props.hasOwnProperty("value")) {
			return;
		}
		if (!!props.value) {
			setA(props.value[0]);
			setB(props.value[1]);
		}
	}, [props]);
	return (
		<Input.Group compact>
			<Input
				suffix={"%"}
				style={{ width: `calc((100% - 30px)/2 )`, textAlign: "center" }}
				placeholder="最小值"
				onInput={(e) => testInput(e, "A")}
				value={A}
			/>
			<Input
				placeholder="~"
				disabled
				style={{
					width: "30px",
					borderLeft: 0,
					borderRight: 0,
					pointerEvents: "none",
					backgroundColor: "white",
				}}
			/>
			<Input
				suffix={"%"}
				style={{
					width: `calc((100% - 30px)/2 )`,
					textAlign: "center",
					borderLeft: 0,
				}}
				placeholder="最大值"
				onInput={(e) => testInput(e, "B")}
				value={B}
			/>
		</Input.Group>
	);
}

export default CommonRange;
